<?

class newprinter_ctl_admin_receipts_print extends ome_ctl_admin_receipts_print {

    var $name = "发货中心";
    var $workground = "delivery_center";

    /**
     * 定义tab菜单
     * 
     * @return string
     */
    function _views() {
        $mdl_delivery = $this->app->model('delivery');
        $logiLists = $mdl_delivery->getLogi_name();

        $sub_menu[0] = array('label' => app::get('ome')->_('所有单据'), 'filter' => 'false', 'optional' => false);

        $i = 0;
        foreach ($logiLists as $key => $logi) {

            $sub_menu[$logi['logi_id'] + 1] = array('label' => app::get('ome')->_($logi['logi_name']),
                'filter' => array('logi_id' => $logi['logi_id']));
        }

        $filter = $this->getBaseFilter($this->_getStatus());

        $deliveryTable = $mdl_delivery->table_name(1);
        $deliveryItemTable = app::get('ome')->model('delivery_items')->table_name(1);
        $db = kernel::database();

        foreach ($sub_menu as $k => $v) {

            $sub_menu[$k]['filter'] = $v['filter'] ? $v['filter'] : array();
            if (!is_array($sub_menu[$k]['filter']))
                $sub_menu[$k]['filter'] = array($sub_menu[$k]['filter']);
            $sub_menu[$k]['filter'] = array_merge($sub_menu[$k]['filter'], $filter);
            $sub_menu[$k]['addon'] = $mdl_delivery->count($sub_menu[$k]['filter']);

            $sub_menu[$k]['href'] = 'index.php?app=newprinter&ctl=admin_receipts_print&act=index&view=' . $k . "&status=" . $_GET['status'];
        }
        return $sub_menu;
    }

    /**
     * 获取基本的数据过滤条件
     * s
     * @return string
     */
    function getBaseFilter($status) {

        $filter['parent_id'] = 0;
        //$filter['status'] = array('succ','failed','progress','timeout','ready','stop');
        $filter['type'] = 'normal';
        $filter['disabled'] = 'false';
        $filter['status'] = array('ready', 'progress', 'succ');

        /*
         * 获取操作员管辖仓库
         */
        $oBranch = &app::get('ome')->model('branch');
        $is_super = kernel::single('desktop_user')->is_super();
        if (!$is_super) {
            $branch_ids = $oBranch->getBranchByUser(true);
            if ($branch_ids) {
                $filter['branch_id'] = $branch_ids;
            } else {

                $filter['branch_id'] = 'false';
            }
        }

        $baseFilter = $this->_getStatusFilter($status);

        $filter = array_merge($filter, $baseFilter);

        return $filter;
    }

    function _getStatusCaption($status) {

        $_captions = array('0' => '全部未打印',
    '7' => '打印未完成',
    '1' => '货到付款',
    '2' => '款到发货',
    '3' => '未录入快递单号',
    '4' => '未发货',
    '5' => '已发货',
    '6' => '全部');

        return (!isset($_captions[$status])) ? $_captions[0] : $_captions[$status];
    }

    function _getStatusFilter($status) {

        switch ($status) {
            case 0 :
                $filter['stock_status'] = "FALSE";
                $filter['deliv_status'] = "FALSE";
                $filter['expre_status'] = "FALSE";
                break;
            case 7:
                $filter['defined_sql'] = "(stock_status='false' or deliv_status='false' or expre_status='false') and (stock_status='true' or deliv_status='true' or expre_status='true')";
                break;
            case 1:
                $filter['is_cod'] = "TRUE";
                break;
            case 2:
                $filter['is_cod'] = "FALSE";
                break;
            case 3:
                $filter['logi_no'] = 'NULL';
                break;
            case 4:
                $filter['process'] = "FALSE";
                break;
            case 5:
                $filter['process'] = "TRUE";
                break;
            default:
                $filter = array();
                break;
        }

        return $filter;
    }

    function _getViewFilter() {

        $view = intval($_GET['view']);
        //此处最好加上检验
        $mdl_delivery = $this->app->model('delivery');
        $logiLists = $mdl_delivery->getLogi_name();

        foreach ($logiLists as $id => $logi) {

            if ($logi['logi_id'] == $view - 1) {

                return array('logi_id' => $view - 1);
            }
        }
        return array();
    }

    function _getStatus() {

        $status = intval($_GET['status']);

        $status = ($status < 0 || $status > 7) ? 0 : $status;

        return $status;
    }

    /**
     * action index 的入口
     */
    function index() {

        $status = $this->_getStatus();
        $title = $this->_getStatusCaption($status);
        $filter = $this->getBaseFilter($status);

        $actionFix = "&view={$_GET[view]}&status={$status}";

        $params = array(
            'title' => $title,
            'actions' => array(
                array(
                    'label' => '打印备货单',
                    'submit' => 'index.php?app=newprinter&ctl=admin_receipts_print&act=toPrintStock' . $actionFix,
                    'target' => "_blank",
                    'icon' => 'add_new.gif',
                //'onclick' => "alert('test'); return false;",
                ),
                array(
                    'label' => '打印发货单',
                    'submit' => 'index.php?app=newprinter&ctl=admin_receipts_print&act=toPrintMerge' . $actionFix,
                    'target' => '_blank',
                ),
                array(
                    'label' => '打印快递单',
                    'submit' => 'index.php?app=newprinter&ctl=admin_receipts_print&act=toPrintShip' . $actionFix,
                    'target' => '_blank', //"dialog::{width:800,height:600,title:'设置标签'}",//
                ),
                array(
                    'label' => '联合打印',
                    'submit' => 'index.php?app=newprinter&ctl=admin_receipts_print&act=toMergePrint' . $actionFix,
                    'target' => '_blank', //"dialog::{width:800,height:600,title:'设置标签'}",//
                ),
                array(
                    'label' => '导出快递号模板',
                    'href' => 'index.php?app=newprinter&ctl=admin_receipts_print&act=exportTemplate' . $actionFix,
                    'target' => '_blank', //"dialog::{width:800,height:600,title:'设置标签'}",//
                ),
            ),
            'base_filter' => $filter,
            //'base_order' => 'idx_split',
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag' => false,
            'use_buildin_recycle' => false,
            'use_buildin_export' => false,
            'use_buildin_import' => false,
            'use_view_tab' => true,
            'use_buildin_filter' => true,
        );
        $this->finder('newprinter_mdl_delivery', $params);
    }

    /**
     * 打印备货单
     *
     */
    function toPrintStock() {

        $fromItems = $this->_getIds();

        $fromIds = $fromItems['ids'];
        $allItems = $fromItems['items'];
        $idents = $fromItems['queue'];
        //对数据进行检验
        $idsAll = $this->parsePrintIds($fromIds);

        //获取数据
        $idstr = implode(',', $idsAll['ids']);
        $dlyObj = & app::get('ome')->model('delivery');
        $data = $dlyObj->countProduct();
        $rows = $this->fetchStockData($idsAll['ids']);
        $memo = $dlyObj->getOrderMemoByDeliveryId($idstr);

        //显示
        $this->pagedata['err'] = 'false';
        $this->pagedata['allItems'] = $allItems;
        $this->pagedata['idents'] = $idents['itmes'];
        $this->pagedata['ident'] = $idents['ident'];
        $this->pagedata['errIds'] = $idsAll['errIds'];
        $this->pagedata['errInfo'] = $idsAll['errInfo'];
        $this->pagedata['vid'] = $idstr;
        $this->pagedata['time'] = date("Y-m-d H:i:s");
        $this->pagedata['data'] = $data;
        $this->pagedata['rows'] = $rows;
        $this->pagedata['memo'] = unserialize($memo);
        //$this->pagedata['total'] = $count;
        $this->pagedata['base_dir'] = kernel::base_url();
        
        $this->singlepage('admin/delivery/stock_print.html');
        $this->display('admin/delivery/print.html');
    }

    /**
     * 联合打印
     * 
     */
    function toMergePrint() {
        $fromItems = $this->_getIds();

        $fromIds = $fromItems['ids'];
        $allItems = $fromItems['items'];
        $idents = $fromItems['queue'];

        $idsAll = $this->parsePrintIds($fromIds);
        $ids = $idsAll['ids'];
        $idstr = implode(',', $ids);

        $items = array();
        foreach ($ids as $id) {

            $item = $this->fetchDeliveryMergeData($id);
            if (!empty($item))
                $items[$id] = $item;
        }

        $this->pagedata['err'] = 'false';
        $this->pagedata['allItems'] = $allItems;
        $this->pagedata['idents'] = $idents['itmes'];
        $this->pagedata['ident'] = $idents['ident'];
        $this->pagedata['errIds'] = $idsAll['errIds'];
        $this->pagedata['errInfo'] = $idsAll['errInfo'];
        $this->pagedata['vid'] = $idstr;
        $this->pagedata['items'] = $items;
        $this->pagedata['base_dir'] = kernel::base_url();
        $this->pagedata['time'] = date("Y-m-d H:i:s");        
        $this->singlepage('admin/delivery/merge_print.html');
        $this->display('admin/delivery/print.html');
    }

    /**
     * 发货单
     */
    function toPrintMerge() {

        $fromItems = $this->_getIds();

        $fromIds = $fromItems['ids'];
        $allItems = $fromItems['items'];
        $idents = $fromItems['queue'];

        $idsAll = $this->parsePrintIds($fromIds);
        $ids = $idsAll['ids'];
        $idstr = implode(',', $ids);

        //获取每个发货单的数据
        $items = array();
        foreach ($ids as $id) {

            $item = $this->fetchDeliveryData($id);
            if (!empty($item))
                $items[$id] = $item;
        }

        $this->pagedata['err'] = 'false';
        $this->pagedata['allItems'] = $allItems;
        $this->pagedata['idents'] = $idents['itmes'];
        $this->pagedata['ident'] = $idents['ident'];
        $this->pagedata['errIds'] = $idsAll['errIds'];
        $this->pagedata['errInfo'] = $idsAll['errInfo'];
        $this->pagedata['vid'] = $idstr;
        $this->pagedata['items'] = $items;
        $this->pagedata['base_dir'] = kernel::base_url();
        $this->pagedata['time'] = date("Y-m-d H:i:s");      
        $this->singlepage('admin/delivery/delivery_print.html');
        $this->display('admin/delivery/print.html');
    }

    /**
     * 快递单打印
     */
    function toPrintShip($dly_id=0) {

        $fromItems = $this->_getIds();

        $fromIds = $fromItems['ids'];
        $allItems = $fromItems['items'];
        $idents = $fromItems['queue'];

        $idsAll = $this->parsePrintIds($fromIds);
        $ids = $idsAll['ids'];
        $idstr = implode(',', $ids);

        $shipData = $this->fetchShipData($ids);

        foreach ($shipData['data'] as $key => $val) {

            $shipData['data'][$key]['ident'] = $idents['itmes'][$val['delivery_id']];
            $data = array();
            foreach(kernel::servicelist('ome.service.template') as $object=>$instance){
                $tmp = $instance->getElementContent($shipData['data'][$key]);
                $shipData['data'][$key] = array_merge($shipData['data'][$key], $tmp);
            }
        }

        $printTmpl = & app::get('ome')->model('print_tmpl');
        $dlyObj = & app::get('ome')->model('delivery');
        $this->pagedata['data'] = addslashes($dlyObj->array2xml2($shipData['data'], 'data'));
        $this->pagedata['order_number'] = count($ids);
        $this->pagedata['prt_tmpl'] = $printTmpl->dump($shipData['dly_tmpl_id'], 'prt_tmpl_width,prt_tmpl_height,prt_tmpl_data,file_id');

        /* 修改的地方 */
        if ($this->pagedata['prt_tmpl']['file_id']) {
            $this->pagedata['tmpl_bg'] = 'index.php?app=ome&ctl=admin_delivery_print&act=showPicture&p[0]=' . $this->pagedata['prt_tmpl']['file_id'];
        }
        $this->pagedata['err'] = 'false';
        $this->pagedata['vid'] = $idstr;

        $this->pagedata['allItems'] = $allItems;

        $this->pagedata['idents'] = $idents['itmes'];
        $this->pagedata['ident'] = $idents['ident'];

        $this->pagedata['errIds'] = $idsAll['errIds'];
        $this->pagedata['errInfo'] = $idsAll['errInfo'];

        $this->pagedata['dpi'] = 96;
        $this->pagedata['count'] = sizeof($ids);
        $this->pagedata['ids'] = $ids;
        $this->pagedata['idd'] = $shipData['idd'];
        $this->pagedata['logid'] = $shipData['logid'];
        $this->pagedata['base_dir'] = kernel::base_url();

        $this->singlepage("admin/delivery/express_print.html");
    }

    /**
     * 获取快递单数据
     */
    function fetchShipData($ids) {

        $dlyObj = & app::get('ome')->model('delivery');
        $dly_corpObj = & app::get('ome')->model('dly_corp');

        $shop = array();
        $idd = array();
        $logid = array();
        foreach ($ids as $id) {

            $dly = $dlyObj->dump($id, '*');

            if (!is_array($dly))
                continue;

            $row = $dly_corpObj->dump($dly['logi_id'], 'prt_tmpl_id');

            $dly['prt_tmpl_id'] = $row['prt_tmpl_id'];
            $dly_tmpl_id = $row['prt_tmpl_id'];

            $idd[] = array('delivery_id' => $dly['delivery_id'], 'delivery_bn' => $dly['delivery_bn']);
            $logid[$id] = $dly['logi_no'];

            if (!isset($shop[$dly['shop_id']])) {

                $shop[$dly['shop_id']] = $dlyObj->getShopInfo($dly['shop_id']);
            }

            $data = $dly;
            /*
             * 收货人信息
             */
            $data['ship_name'] = $dly['consignee']['name'];
            $data['ship_addr'] = $dly['consignee']['addr'];
            $data['ship_tel'] = $dly['consignee']['telephone'];
            $data['ship_mobile'] = $dly['consignee']['mobile'];
            $data['ship_zip'] = $dly['consignee']['zip'];
            $data['ship_area_0'] = $dly['consignee']['province'];
            $data['ship_area_1'] = $dly['consignee']['city'];
            $data['ship_area_2'] = $dly['consignee']['district'];

            $t = time() + ($GLOBALS['user_timezone'] - SERVER_TIMEZONE) * 3600;
            $data['date_y'] = date('Y', $t);
            $data['date_m'] = date('m', $t);
            $data['date_d'] = date('d', $t);
            /*
             * 发货人信息
             */
            $area = kernel::single('base_view_helper')->modifier_region($shop['area']);
            $area = explode('-', $area);
            $data['dly_area_0'] = $area[0];
            $data['dly_area_1'] = $area[1];
            $data['dly_area_2'] = $area[2];
            $data['dly_address'] = $shop[$dly['shop_id']]['addr'];
            $data['dly_tel'] = $shop[$dly['shop_id']]['tel'];
            $data['dly_mobile'] = $shop[$dly['shop_id']]['mobile'];
            $data['dly_zip'] = $shop[$dly['shop_id']]['zip'];
            $data['dly_name'] = $shop[$dly['shop_id']]['default_sender'];
            $data['shop_name'] = $shop[$dly['shop_id']]['name'];

            $mydata[] = $data;
        }

        return array('data' => $mydata, 'idd' => $idd,
            'logid' => $logid, 'dly_tmpl_id' => $dly_tmpl_id);
    }

    /**
     * 获取合并订单数据
     *
     * @param Integer $id 发货单ID
     * @return Array
     */
    function fetchDeliveryMergeData($id) {

        $dlyObj = & app::get('ome')->model('delivery');
        $orderObj = & app::get('ome')->model('orders');
        $dly_ipObj = & app::get('ome')->model('dly_items_pos');
        $branch_pObj = & app::get('ome')->model('branch_pos');
        $pObj = & app::get('ome')->model('products');
        $data = $dlyObj->dump($id, '*', array('delivery_items' => array('*'), 'delivery_order' => array('*')));
        if (is_array($data)) {
            foreach ($data['delivery_items'] as $k => $v) {

                $total += $v['number'];
                $pos = array();
                $dip_data = $dly_ipObj->getList('pos_id,num', array('item_id' => $v['item_id']), 0, -1);

                foreach ($dip_data as $it) {
                    $bp = $branch_pObj->dump($it['pos_id'], 'store_position');
                    $tmpp['store_position'] = $bp['store_position'];
                    $tmpp['num'] = $it['num'];
                    //以货位为下标，便于排序
                    $pos[$bp['store_position']] = $tmpp;
                }
                //排序一个货品的货位，取最前的为优先货位
                ksort($pos);
                reset($pos);
                $itemKey = key($pos) . $k;
                $s_delivery_items[$itemKey] = $data['delivery_items'][$k];
                $s_delivery_items[$itemKey]['pos'] = $pos;

                $p = $pObj->dump($v['product_id']);
                $s_delivery_items[$itemKey]['spec_info'] = $p['spec_info'];
                $s_delivery_items[$itemKey]['name'] = $p['name'];
            }

            unset($data['delivery_items']);
            $data['delivery_items'] = $s_delivery_items;
            //排序整个单据数据
            ksort($data['delivery_items']);

            $tmp = app::get('ome')->model('members')->dump($data['member_id'], 'name,mobile,tel');
            $data['member_name'] = $tmp['contact']['name'];
            $t_tel = array();
            if ($tmp['contact']['phone']['telephone']) {
                $t_tel[] = $tmp['contact']['phone']['telephone'];
            }
            if ($tmp['contact']['phone']['mobile']) {
                $t_tel[] = $tmp['contact']['phone']['mobile'];
            }
            $order_bn = array();
            if ($data['delivery_order'])
                foreach ($data['delivery_order'] as $v) {
                    $order = $orderObj->dump($v['order_id'], 'order_bn,custom_mark,mark_text');
                    if ($order['custom_mark']) {
                        $mark = unserialize($order['custom_mark']);
                        if (is_array($mark) || !empty($mark))
                            foreach ($mark as $im) {
                                $data['_mark'][$order['order_bn']][] = $im;
                            }
                    }
                    if ($order['mark_text']){
                        $mark = unserialize($order['mark_text']);
                        if (is_array($mark) || !empty($mark))
                            foreach ($mark as $im){
                                $data['_mark_text'][$order['order_bn']][] = $im;
                            }
                    }
                    $order_bn[] = $order['order_bn'];
                    // -- lxqun -- 2010-12-1 17:15:32
                    $ol=$orderObj->getItemList($v['order_id']);
                          foreach($ol as $oi){
                              $orderItems[$v['delivery_id']][$oi['product_id']]=$oi;
                          }
                          unset($ol);
                }
            $data['order_bn'] = implode(" , ", $order_bn);
            if ($t_tel)
                $data['member_tel'] = implode(" / ", $t_tel);
            // 发货 货品价格 --lxqun --2010-12-1 17:20:12
                $delivery_total_nums = 0;
                foreach ($data['delivery_items'] as $k => $item){
                    $oi=$orderItems[$item['delivery_id']][$item['product_id']];
                    $data['delivery_items'][$k]['price']=$oi['price'];
                    $data['delivery_items'][$k]['amount']=$oi['amount'];
                    $delivery_total_nums += $item['number'];
                }
                $data['delivery_total_nums'] = $delivery_total_nums;
                $data['order_total_amount'] = $dlyObj->getAllTotalAmountByDelivery($data['delivery_order']);
            return $data;
        } else {

            return null;
        }
    }

    /**
     * 获取发货单数据
     *
     * @param Integer $deliveryId 发货单ID
     * @rteun Mixed
     */
    function fetchDeliveryData($deliveryId) {

        $dlyObj = &app::get('ome')->model('delivery');
        $orderObj = &app::get('ome')->model('orders');
        $pObj = &app::get('ome')->model('products');

        $data = $dlyObj->dump($deliveryId, '*', array('delivery_items' => array('*'), 'delivery_order' => array('*')));

        if (is_array($data)) {
            foreach ($data['delivery_items'] as $k => $item) {
                $p = $pObj->dump($item['product_id']);
                $data['delivery_items'][$k]['spec_info'] = $p['spec_info'];
            }
            $tmp = app::get('ome')->model('members')->dump($data['member_id'], 'name,mobile,tel');
            $data['member_name'] = $tmp['contact']['name'];
            $t_tel = array();
            if ($tmp['contact']['phone']['telephone']) {
                $t_tel[] = $tmp['contact']['phone']['telephone'];
            }
            if ($tmp['contact']['phone']['mobile']) {
                $t_tel[] = $tmp['contact']['phone']['mobile'];
            }
            $order_bn = array();
            if ($data['delivery_order'])
                foreach ($data['delivery_order'] as $v) {
                    $order = $orderObj->dump($v['order_id'], 'order_bn,custom_mark');
                    if ($order['custom_mark']) {
                        $mark = unserialize($order['custom_mark']);
                        if (is_array($mark) || !empty($mark))
                            foreach ($mark as $im) {
                                $data['_mark'][$order['order_bn']][] = $im;
                            }
                    }
                    $order_bn[] = $order['order_bn'];
                    // -- lxqun -- 2010-12-1 17:15:32
                    $ol=$orderObj->getItemList($v['order_id']);
                          foreach($ol as $oi){
                              $orderItems[$v['delivery_id']][$oi['product_id']]=$oi;
                          }
                          unset($ol);
                }
            $data['order_bn'] = implode(" , ", $order_bn);
            if ($t_tel)
                $data['member_tel'] = implode(" / ", $t_tel);
            // 发货 货品价格 --lxqun --2010-12-1 17:20:12
                foreach ($data['delivery_items'] as $k => $item){
                    $oi=$orderItems[$item['delivery_id']][$item['product_id']];
                    $data['delivery_items'][$k]['price']=$oi['price'];
                    $data['delivery_items'][$k]['amount']=$oi['amount'];
                }
            return $data;
        } else {

            return null;
        }
    }

    /**
     * 检查发货单是否可操作
     *
     * @param Integer $dly_id
     * @param String $errMsg  引用，用于返回错误信息
     * @return Boolean
     */
    function checkOrderStatusEx($dly_id, &$errMsg) {
        $Objdly = &app::get('ome')->model('delivery');
        $delivery = $Objdly->dump($dly_id);

        //检查发货单状态，如是合并而成的发货单位
        if (!$Objdly->existOrderStatus($dly_id, $delivery['is_bind'])) {

            $errMsg = "发货单已无法操作，请到订单处理中心处理";
            return false;
        }
        if (!$Objdly->existOrderPause($dly_id, $delivery['is_bind'])) {
            $errMsg = "发货单相关订单已暂停，请到订单处理中心处理";
            return false;
        }

        return true;
    }

    /**
     * 获取所有要操作发货单的内容
     *
     * @return Array
     */
    function _getIds() {

        $ids = array();
        $fromIds = $_POST['delivery_id'];
        $isSelected = $_POST['isSelectedAll'];

        $dlyObj = & $this->app->model('delivery');
        if ($isSelected == '_ALL_') {

            $filter = $_POST;
            unset($filter['_finder']);
            unset($filter['isSelectedAll']);
            $filter['status'] = array('ready', 'progress', 'succ');
            $baseFilter = $this->_getStatusFilter($this->_getStatus());
            $filter = array_merge($filter, $baseFilter);
            $viewFilter = $this->_getViewFilter();
            $filter = array_merge($filter, $viewFilter);
        } else {
            $filter['delivery_id'] = $fromIds;
        }

        $filter['parent_id'] = 0;
        $filter['disabled'] = 'false';
        
        $filter['type'] = 'normal';
        
        $rows = $dlyObj->getList('*', $filter, 0, -1);
        $logi = array();
        foreach ($rows as $row) {
            $logi[$row['logi_id']]++;
            $ids['ids'][] = $row['delivery_id'];
            $ids['items'][$row['delivery_id']] = $row;
        }

        //检查是否是同一快递公司
        if (count($logi) > 1) {
            $this->message("当前系统不支持同时打印二种不同快递类型的单据，请重新选择后再试！");
            exit;
        }


        if (!empty($ids['ids']))
            sort($ids['ids']);

        $queueObj = new newprinter_queue();
        $ids['queue'] = $queueObj->fetchPrintQueue($ids['ids']);
        return $ids;
    }

    function parsePrintIds($ids) {

        $result = array(
            'ids' => array(), //可用于打印的ID
            'errIds' => array(), //不能胜于打印的数据
            'errInfo' => array(), //所有错误信息
        );



        $dlyObj = & app::get('ome')->model('delivery');
        foreach ($ids as $id) {

            $hasError = false;
            //检查当前订单的状态是不是可以打印
            if (!$this->checkOrderStatusEx($id, $errMsg)) {
                //状态有问题的订单是肯定不要打印的
                $result['errIds'][] = $id;
                $result['errInfo'][$id] = $errMsg;
                $hasError = true;
            } else {

                $result['ids'][] = $id;
            }
            if (!$hasError) {
                //检查库存
                $dly = $dlyObj->dump($id, '*', array('delivery_items' => array('*')));
                foreach ($dly['delivery_items'] as $item) {
                    $re = $dlyObj->existStockIsPlus($item['product_id'], $item['number'], $item['item_id'], $dly['branch_id'], $err, $item['bn']);
                    if (!$re) {
                        $result['errIds'][] = $id;
                        $result['errInfo'][$id] .= $err . "&nbsp;,&nbsp;";
                        $hasError = true;
                    }
                }
                //库存有问题的单据认为是要打印的
                if (!in_array($id, $result['ids']))
                    $result['ids'][] = $id;
            }
        }

        if (empty($result['ids'])) {
            if (!empty($result['errIds'])) {

                $msg = sprintf("你所选择的 %d 张单据状态异常，无法打印，本次操作中止！", count($result['errIds']));
            } else {

                $msg = '你没有选择要打印的单据，请重新选择后再试！s';
            }
            $this->message($msg);
            exit;
        }

        return $result;
    }

    function fetchStockData($ids) {

        $rows = array();
        if (is_array($ids)) {
            $dlyObj = & app::get('ome')->model('delivery');
            foreach ($ids as $k => $v) {
                $daa = $dlyObj->getProductPosByDeliveryId($v);
                if (!$daa)
                    continue;
                foreach ($daa as $i) {

                    //该key做为排序关键字，以 货位、货号排序
                    $key = $i['store_position'] . $i['bn'];

                    $rows[$key]['bn'] = $i['bn'];
                    $rows[$key]['name'] = $i['name'];
                    $rows[$key]['store_position'] = $i['store_position'];
                    $rows[$key]['product_name'] = $i['product_name'];
                    $rows[$key]['spec_info'] = $i['spec_info'];
                    $rows[$key]['num'] += $i['num'];
                    $rows[$key]['boxs'][] = '<' . ($k + 1) . '(' . $i['num'] . ')>';
                    $rows[$key]['box'] = implode(',', $rows[$key]['boxs']);
                }
            }
        }

        //以数组为下标进行排序
        if (is_array($rows))
            ksort($rows);

        return $rows;
    }

    function message($msg) {

        $this->pagedata['err'] = 'true';
        $this->pagedata['base_dir'] = kernel::base_url();
        $this->pagedata['time'] = date("Y-m-d H:i:s");
        $this->pagedata['msg'] = $msg;
        $this->singlepage('admin/delivery/message.html');
        $this->display('admin/delivery/print.html');
    }
}